package nl.grol.yakshop.web.servlet;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nl.grol.yakshop.binding.MyYakShopModule;
import nl.grol.yakshop.domain.model.YakHerd;
import nl.grol.yakshop.domain.model.YakI;
import nl.grol.yakshop.domain.repository.Repository;
import nl.grol.yakshop.util.InvalidInputException;
import nl.grol.yakshop.web.servlet.json.JsonConverter;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;

@Singleton
@SuppressWarnings("serial")
public class HerdServlet extends BaseJsonServlet {
    private static final Logger LOGGER = Logger.getLogger(HerdServlet.class.getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
    	int httpResponseStatus = 500;

		try {

			/*
			 * Parse request
			 */
			Integer dayOffsetSinceShopOpening = extractLastPathSegmentFromRequest(req);
			
			/*
			 * Get services from guice
			 */
			Injector injector = Guice.createInjector(new MyYakShopModule());
			Repository repository = injector.getInstance(Repository.class);
			
			/*
			 * Get data
			 */
			YakHerd herd = repository.getHerd();
			
			/*
			 * Log for debugging
			 */
			for( YakI yak : herd.getYaks() ) {
				LOGGER.info(yak.toString() );
			}
			
			/*
			 * Create json response
			 */
			String herdAsJson = JsonConverter.makeJsonHerd(dayOffsetSinceShopOpening, 
									herd.getYaks() );
			
			/*
			 * Write to response body
			 */
			writeSuccessResponse( req, resp, 200, herdAsJson);
		
		} catch( InvalidInputException exc ) {
			
				LOGGER.warning("Error parsing day from request " + exc.getMessage() );
				httpResponseStatus = 400;
				writeErrorResponse( req, resp, httpResponseStatus, exc);

		} catch( Exception exc ) {
			
			LOGGER.warning("Undefined error " + exc.getMessage() );
			/*
			 * Report error
			 */
			writeErrorResponse( req, resp, httpResponseStatus, exc);

		}

	}
	

}
